package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.file.FileUploadUtils;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.Task;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.*;

@Service
@Transactional
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;
    @Autowired
    private ServiceItemMapper serviceItemMapper;
    @Autowired
    private TaskService taskService;

    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<CarPackageAudit>(carPackageAuditMapper.selectForList(qo));
    }

    @Override
    public InputStream processImg(Long id) {
        //根据id查询出carPackageAudit的数据
        //判断是否在审核中的情况 如果审核中则需要高亮显示
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        //判断状态
        List<String> list = new ArrayList<>();
        if (CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())){
            //查询出任务中的节点.进行高亮显示
            list = runtimeService.getActiveActivityIds(carPackageAudit.getInstanceId());

        }else {
            list = Collections.EMPTY_LIST;
        }
        //将流程图画图显示出去
        //查询出bpmnInfo对象
        BpmnInfo bpmnInfo = bpmnInfoMapper.selectByPrimaryKey(carPackageAudit.getBpmnInfoId());
        ProcessDiagramGenerator processDiagramGenerator = new DefaultProcessDiagramGenerator();
        InputStream inputStream = processDiagramGenerator.generateDiagram(repositoryService.getBpmnModel(bpmnInfo.getActProcessId()),
                list,
                Collections.emptyList(),
                "宋体",
                "宋体",
                "宋体");
        return inputStream;
    }

    @Override
    public void cancelApply(Long id) {

        //根据id查询出来数据
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        //判断状态是否是在审核中的状态
        if (!CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())){
            throw new BusinessException("非法操作");
        }
        //将carPackageAudit中的数据状态更改为撤销状态
        carPackageAuditMapper.changeStatus(id,CarPackageAudit.STATUS_CANCEL);
        //将serviceItem中的套餐状态更改为初始化状态.
        serviceItemMapper.changeAuditStutas(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_INIT);
        //删除流程实例
        //获取runtimeService 用来删除流程实例
        runtimeService.deleteProcessInstance(carPackageAudit.getInstanceId(),"删除");
    }

    @Override
    @Transactional
    public void audit(Long id, Integer auditStatus, String info) {
        //根据传过来的id查询出carpackage
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        //判断对象的状态是否在一个审核中的状态,如果不是则抛出异常
        if (!CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())){
            throw new BusinessException("非法操作");
        }
        //完成任务 设置一个流程变量
        Map<String,Object> map = new HashMap<>();
        map.put("auditStatus",auditStatus);
        //根据流程实例id查询当前的当前的任务
        Task task = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();
        //完成任务
        taskService.complete(task.getId(),map);
        if (auditStatus!=2){
            //审核拒绝
            //修改carPackageAudit 状态为审核拒绝 修改审核时间 修改审核审核人
            carPackageAudit.setStatus(CarPackageAudit.STATUS_REJECT);

            carPackageAudit.setInfo(carPackageAudit.getInfo() +"<==> "+ShiroUtils.getUser().getUserName()+" 审批拒绝 ->意见: " + info );
            //修改服务单状态为一个重新审核的状态
            //修改审核人
            carPackageAudit.setAuditorId(ShiroUtils.getUserId());
            serviceItemMapper.changeAuditStutas(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_REPLY);
        }else {
            //审核通过
            Task nextTask = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();
            if (nextTask==null){
                //设置carPackageAudit状态为审核通过
                carPackageAudit.setStatus(CarPackageAudit.STATUS_PASS);
                //设置服务单项的审核状态为审核通过
                //修改审核人
                carPackageAudit.setAuditorId(ShiroUtils.getUserId());
                serviceItemMapper.changeAuditStutas(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_APPROVED);
            }else {
                //更改审批人
                String assignee = nextTask.getAssignee();
                carPackageAudit.setAuditorId(Long.parseLong(assignee));
            }
            carPackageAudit.setInfo(carPackageAudit.getInfo() +"<==> "+ShiroUtils.getUser().getUserName()+" 审批拒绝 ->意见: " + info );
        }

        //修改审核时间
        carPackageAudit.setAuditTime(new Date());
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);

    }


}
